package com.soulgame.sms.sms;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.telephony.SmsManager;
import android.util.Log;

import com.soul.sdk.utils.SGDebug;

/**
 * @author lch
 * @version Create time：2017-4-1
 * @类说明： 普通短信发送
 */
public class SendSmsUtils {

	public static final int SEND_SMS_RESULT_SUCCESS = 0;
	public static final int SEND_SMS_RESULT_FAIL = 1;
	public static final int SEND_SMS_RESULT_TIME_OUT = 2;

	private static final String SMS_SEND_ACTION = "com.soulgame.send.sms";
	private static final String DELIVERED_SMS_ACTION = "com.soulgame.delivered.sms";
	private static final String BUNDLE_KEY_SEND_SMS_ID = "Key_SendSmsId";
	// 超时时间 毫秒
	private static final long TIMER_OUT = 15000;
	//
	private static Map<String, Object> mObjectParamMap = new HashMap<String, Object>(2);
	private static Map<String, ISendSmsListener> mSendSmsListenerMap = new HashMap<String, ISendSmsListener>(2);
	private static Map<BroadcastReceiver, Context> mBroadcastReceiverMap = new HashMap<BroadcastReceiver, Context>(2);

	public enum SendSmsType {
		Text, Data
	}

	// =========================================================
	/**
	 * 发送 Text 类型短信 sendTextMessage
	 * 
	 * @param pContext
	 * @param pAddress
	 *            发送地址
	 * @param pSmsContent
	 *            短信内容
	 * @param pObjectParam
	 *            透传参数，在支付结果回调监听接口原样返回
	 *            {@link ISendSmsListener#onSentResult(int, Object)}
	 * @param pSendSmsListener
	 *            支付结果监听
	 */
	public static void sendSms(Context pContext, String pAddress, String pSmsContent, Object pObjectParam,
			ISendSmsListener pSendSmsListener) {
		SendSmsUtils
				.sendSms(pContext, SendSmsType.Text, pAddress, pSmsContent, (short) 0, null, pObjectParam, pSendSmsListener);
	}

	/**
	 * 发送 Data类型短信 sendDataMessage
	 * 
	 * @param pContext
	 * @param pAddress
	 *            发送地址
	 * @param pSmsPort
	 *            发送端口
	 * @param data
	 *            发送数据
	 * @param pObjectParam
	 *            透传参数，在支付结果回调监听接口原样返回
	 *            {@link ISendSmsListener#onSentResult(int, Object)}
	 * @param pSendSmsListener
	 *            支付结果监听
	 */
	public static void sendSms(Context pContext, String pAddress, short pSmsPort, byte[] data, Object pObjectParam,
			ISendSmsListener pSendSmsListener) {
		SendSmsUtils.sendSms(pContext, SendSmsType.Data, pAddress, null, pSmsPort, data, pObjectParam, pSendSmsListener);
	}

	private static void sendSms(Context pContext, SendSmsType pSendSmsType, String pAddress, String pSmsContent,
			short pSmsPort, byte[] pData, Object pObjectParam, ISendSmsListener pSendSmsListener) {
		// 数据保存处理
		String sendSmsId = String.valueOf(System.currentTimeMillis());
		mObjectParamMap.put(sendSmsId, pObjectParam);
		mSendSmsListenerMap.put(sendSmsId, pSendSmsListener);
		//
		SendSmsData sendSmsData = new SendSmsData();
		sendSmsData.mSendSmsId = sendSmsId;
		sendSmsData.mContext = pContext;
		sendSmsData.mSendSmsType = pSendSmsType;
		sendSmsData.mAddress = pAddress;
		sendSmsData.mSmsContent = pSmsContent;
		sendSmsData.mSmsPort = pSmsPort;
		sendSmsData.mData = pData;
		sendSmsData.mObjectParam = pObjectParam;
		sendSmsData.mSendSmsListener = pSendSmsListener;
		//
		SendSmsUtils.sendSms(sendSmsData);
	}

	private static void sendSms(SendSmsData pSendSmsData) {
		// 开始发短信
		BroadcastReceiver aSendSmsReceiver = getSendSmsReceiver(pSendSmsData);
		SendSmsUtils.sendSms(pSendSmsData, aSendSmsReceiver);
		// 处理超时
		SendSmsUtils.doTimeOutTask(pSendSmsData, aSendSmsReceiver);
	}

	public static void sendSms(SendSmsData pSendSmsData, BroadcastReceiver pSendSmsReceiver) {
		// 确保 此接收器 只接收这次发短信的情况，一一对应;所以 +pSendSmsData.mSendSmsId
		String send_action = SMS_SEND_ACTION + pSendSmsData.mSendSmsId;
		IntentFilter sentFilter = new IntentFilter(send_action);
		// 注册发送短信监听的广播
		pSendSmsData.mContext.registerReceiver(pSendSmsReceiver, sentFilter);
		// 把广播装进map，用于退出时 处理未来得及取消注册的情况。
		mBroadcastReceiverMap.put(pSendSmsReceiver, pSendSmsData.mContext);
		//
		Intent sentIntent = new Intent(send_action);
		sentIntent.putExtra(BUNDLE_KEY_SEND_SMS_ID, pSendSmsData.mSendSmsId);
		PendingIntent sentPendingIntent = PendingIntent.getBroadcast(pSendSmsData.mContext, 0, sentIntent, 0);
		//
		Intent deliveryIntent = new Intent(DELIVERED_SMS_ACTION + pSendSmsData.mSendSmsId);
		deliveryIntent.putExtra(BUNDLE_KEY_SEND_SMS_ID, pSendSmsData.mSendSmsId);
		PendingIntent deliveryPendingIntent = PendingIntent.getBroadcast(pSendSmsData.mContext, 0, deliveryIntent, 0);
		//
		SmsManager smsManager = SmsManager.getDefault();

		if (pSendSmsData.mSendSmsType == SendSmsType.Data) {
			smsManager.sendDataMessage(pSendSmsData.mAddress, null, pSendSmsData.mSmsPort, pSendSmsData.mData,
					sentPendingIntent, deliveryPendingIntent);

		} else {
			// TODO 这里没处理短信内容大于 70 的情况，如果大于70一般是 会发送长短信、或者分多条发送。
			//
			smsManager.sendTextMessage(pSendSmsData.mAddress, null, pSendSmsData.mSmsContent, sentPendingIntent,
					deliveryPendingIntent);
		}

	}

	// ===========================================================
	private static void doTimeOutTask(final SendSmsData pSendSmsData, final BroadcastReceiver pBroadcastReceiver) {

		Timer aTimer = new Timer();
		aTimer.schedule(getTimeOutTask(pSendSmsData, pBroadcastReceiver), TIMER_OUT);

	}

	private static TimerTask getTimeOutTask(final SendSmsData pSendSmsData, final BroadcastReceiver pBroadcastReceiver) {
		return new TimerTask() {

			@Override
			public void run() {
				SGDebug.w(this, "TimerOut mSendSmsId>>>" + pSendSmsData.mSendSmsId);
				// 超时
				SendSmsUtils.unregisterReceiver(pSendSmsData.mContext, pBroadcastReceiver);
				mBroadcastReceiverMap.remove(pBroadcastReceiver);
				SendSmsUtils.callbackSendResult(pSendSmsData.mSendSmsId, SendSmsUtils.SEND_SMS_RESULT_TIME_OUT);
			}
		};

	}

	// ===========================================================
	/**
	 * 发送短信状态 广播接收器
	 * 
	 * @param pSendSmsData
	 * @return
	 */
	private static BroadcastReceiver getSendSmsReceiver(final SendSmsData pSendSmsData) {
		return new BroadcastReceiver() {

			@Override
			public void onReceive(Context context, Intent intent) {
				// 取消广播注册
				SendSmsUtils.unregisterReceiver(context, this);
				mBroadcastReceiverMap.remove(this);

				String action = intent.getAction();
				String sendSmsId = intent.getStringExtra(BUNDLE_KEY_SEND_SMS_ID);

				SGDebug.d(this, "action>>>" + action);
				SGDebug.d(this, "sendSmsId>>>" + sendSmsId);

				// 发送短信状态
				if (getResultCode() == Activity.RESULT_OK) {
					// 短信发送成功
					SendSmsUtils.callbackSendResult(pSendSmsData.mSendSmsId, SendSmsUtils.SEND_SMS_RESULT_SUCCESS);

				} else {
					// 短信发送失败
					SendSmsUtils.callbackSendResult(pSendSmsData.mSendSmsId, SendSmsUtils.SEND_SMS_RESULT_FAIL);
				}

			}
		};
	}

	// ===========================================================

	/**
	 * 发送结果回调处理
	 * 
	 * @param pSendSmsId
	 * @param pSendSmsResultCode
	 */
	private static void callbackSendResult(String pSendSmsId, int pSendSmsResultCode) {
		ISendSmsListener iSendSmsListener = mSendSmsListenerMap.get(pSendSmsId);
		if (iSendSmsListener != null) {
			Object objectParam = mObjectParamMap.get(pSendSmsId);
			mSendSmsListenerMap.remove(pSendSmsId);
			mObjectParamMap.remove(pSendSmsId);
			iSendSmsListener.onSentResult(pSendSmsResultCode, objectParam);
		}
	}

	// =========================================================
	public static class SendSmsData {
		public String mSendSmsId;
		public Context mContext;
		public SendSmsType mSendSmsType;
		public String mAddress;
		public String mSmsContent;
		public short mSmsPort;
		public byte[] mData;
		public Object mObjectParam;
		public ISendSmsListener mSendSmsListener;
	}

	public interface ISendSmsListener {
		/**
		 * 支付结果回调
		 * 
		 * @param pSendSmsResultCode
		 * @param pObjectParam
		 *            透传参数，#sendSms 发送短信时传入的透传参数这里原样返回
		 */
		public void onSentResult(int pSendSmsResultCode, Object pObjectParam);

	}

	private static void unregisterReceiver(Context pContext, BroadcastReceiver pBroadcastReceiver) {
		try {
			pContext.unregisterReceiver(pBroadcastReceiver);
		} catch (Exception e) {
			Log.w("SGLOG", "SendSmsUtils>>>" + e.toString());
		}
	}

	/**
	 * app 退出时\ 取消注册广播。
	 */
	public static void onDestroy() {
		try {
			if (mBroadcastReceiverMap != null && !mBroadcastReceiverMap.isEmpty()) {
				for (BroadcastReceiver broadcastReceiver : mBroadcastReceiverMap.keySet()) {
					SendSmsUtils.unregisterReceiver(mBroadcastReceiverMap.get(broadcastReceiver), broadcastReceiver);
				}
			}
			mBroadcastReceiverMap = null;
			mObjectParamMap = null;
			mSendSmsListenerMap = null;
		} catch (Exception e) {
		}
	}
}
